@echo off
:: 考试系统健康检查和自动重启脚本
:: 建议配置为Windows任务计划程序，每5分钟运行一次

setlocal enabledelayedexpansion

:: 设置变量
set PROJECT_DIR=%~dp0
set BACKEND_DIR=%PROJECT_DIR%backend
set LOG_FILE=%PROJECT_DIR%logs\health-check.log
set RESTART_COUNT_FILE=%PROJECT_DIR%logs\restart-count.txt
set MAX_RESTART_COUNT=5

:: 创建日志目录
if not exist "%PROJECT_DIR%logs" mkdir "%PROJECT_DIR%logs"

:: 记录检查时间
echo [%date% %time%] 开始健康检查 >> "%LOG_FILE%"

:: 检查后端服务是否运行
netstat -an | find ":3000" | find "LISTENING" > nul
if errorlevel 1 (
    echo [%date% %time%] 警告: 后端服务未运行，尝试重启... >> "%LOG_FILE%"
    goto restart_backend
) else (
    echo [%date% %time%] 后端服务运行正常 >> "%LOG_FILE%"
)

:: 检查HTTP响应
powershell -Command "try { $response = Invoke-WebRequest -Uri 'http://localhost:3000/health' -TimeoutSec 10; if ($response.StatusCode -eq 200) { exit 0 } else { exit 1 } } catch { exit 1 }" > nul
if errorlevel 1 (
    echo [%date% %time%] 警告: 健康检查失败，尝试重启... >> "%LOG_FILE%"
    goto restart_backend
) else (
    echo [%date% %time%] 健康检查通过 >> "%LOG_FILE%"
    goto end
)

:restart_backend
:: 读取重启次数
set /a RESTART_COUNT=0
if exist "%RESTART_COUNT_FILE%" (
    set /p RESTART_COUNT=<"%RESTART_COUNT_FILE%"
)

:: 检查重启次数限制
if !RESTART_COUNT! geq %MAX_RESTART_COUNT% (
    echo [%date% %time%] 错误: 重启次数已达上限 %MAX_RESTART_COUNT%，停止自动重启 >> "%LOG_FILE%"
    goto end
)

:: 增加重启计数
set /a RESTART_COUNT+=1
echo !RESTART_COUNT! > "%RESTART_COUNT_FILE%"

echo [%date% %time%] 第 !RESTART_COUNT! 次重启后端服务... >> "%LOG_FILE%"

:: 停止现有进程
taskkill /f /im node.exe > nul 2>&1

:: 尝试使用PM2重启
call pm2 --version >nul 2>&1
if not errorlevel 1 (
    echo [%date% %time%] 使用PM2重启服务... >> "%LOG_FILE%"
    cd /d "%PROJECT_DIR%"
    call pm2 restart exam-backend
    if not errorlevel 1 (
        echo [%date% %time%] PM2重启成功 >> "%LOG_FILE%"
        goto wait_and_check
    )
)

:: 使用普通方式启动
echo [%date% %time%] 使用普通方式启动服务... >> "%LOG_FILE%"
cd /d "%BACKEND_DIR%"
start /min "" cmd /c "npm start"

:wait_and_check
:: 等待服务启动
timeout /t 10 /nobreak > nul

:: 再次检查服务状态
netstat -an | find ":3000" | find "LISTENING" > nul
if errorlevel 1 (
    echo [%date% %time%] 重启失败，服务仍未运行 >> "%LOG_FILE%"
) else (
    echo [%date% %time%] 重启成功，服务已恢复运行 >> "%LOG_FILE%"
    :: 清除重启计数
    if exist "%RESTART_COUNT_FILE%" del "%RESTART_COUNT_FILE%"
)

:end
echo [%date% %time%] 健康检查结束 >> "%LOG_FILE%"
